package demo.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import demo.entity.Comment;
import demo.entity.User;
import demo.service.CommentService;
import demo.util.ContentFilter;
import demo.util.FormatDate;

@SuppressWarnings("serial")
public class CommentAction extends BaseAction {

	private Comment comment;
	private CommentService commentService;

	private String result;
	
	public String list() throws Exception {
		List<Object[]> list = commentService.queryCommentByWeiboId(comment.getWeiboid());
		List<Map<String, Object>> maps = new ArrayList<Map<String,Object>>();
		for (Object[] objects : list) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", objects[0]);
			map.put("content", ContentFilter.getFiltratedContent((String) objects[1]));
			map.put("time", FormatDate.getFormattedDate((Date) objects[2]));
			map.put("userid", objects[3]);
			map.put("weiboid", objects[4]);
			map.put("weibouserid", objects[5]);
			map.put("nick", objects[6]);
			map.put("avatar", objects[7]);
			maps.add(map);
		}
		JSONArray jsonArray = JSONArray.fromObject(maps);
		this.result = jsonArray.toString();
System.out.println(result);
		return SUCCESS;
	}

	public String publish() throws Exception {
		User user = (User) getSession().get("user");
		getComment().setUserid(user.getId());
		getComment().setTime(new Date());
		commentService.save(comment);
		List<Object[]> list = commentService.queryCommentByWeiboId(comment.getWeiboid());
		Object[] objects = list.get(0);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", objects[0]);
		map.put("content", ContentFilter.getFiltratedContent((String)objects[1]));
		map.put("time", FormatDate.getFormattedDate((Date) objects[2]));
		map.put("userid", objects[3]);
		map.put("weiboid", objects[4]);
		map.put("weibouserid", objects[5]);
		map.put("nick", objects[6]);
		map.put("avatar", objects[7]);
		JSONObject jsonObject = JSONObject.fromObject(map);
		this.result = jsonObject.toString();
System.out.println(result);
		return SUCCESS;
	}
	
	public String delete() throws Exception {
		commentService.delete(comment.getId());
		return null;
	}

	public String method() throws Exception {
		// TODO
		commentService.queryAll();
		return SUCCESS;
	}

	// setters and getters

	public Comment getComment() {
		return comment;
	}

	public void setComment(Comment comment) {
		this.comment = comment;
	}

	public void setCommentService(CommentService commentService) {
		this.commentService = commentService;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public CommentService getCommentService() {
		return commentService;
	}

}
